package com.qiantu.phone.ui.activity;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.hjq.base.BaseActivity;
import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.qiantu.api.db.LLDeviceActionDBManager;
import com.qiantu.api.db.LLDeviceCustomDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.DeviceBaseConfigInfo;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.DeviceBindingData;
import com.qiantu.api.entity.DeviceCustomKeyBean;
import com.qiantu.api.entity.DeviceState;
import com.qiantu.api.entity.SceneDetailBean;
import com.qiantu.api.entity.SwitchBindActionBean;
import com.qiantu.api.entity.SwitchBindBean;
import com.qiantu.api.entity.QueryCodeResultBean;
import com.qiantu.api.entity.UniversalDeviceData;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.api.utils.DeviceInfoParseUtil;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.bean.UISwitchBindBean;
import com.qiantu.phone.ui.adapter.SwitchBindAdapter;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.ui.dialog.WaitFinishDialog;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.utils.TempDataHolder;
import com.qiantu.phone.widget.OperateBindView;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class SwitchBindActivity extends AppActivity {
    public static final int FROM_DEVICE = 0x1;
    public static final int FROM_SCENES = 0x2;
    public static final int FROM_GROUP = 0x3;
    private int type;
    private RecyclerView recyclerView;
    private OperateBindView operateBindView;
    private TitleBar titleBar;
    private BaseDialog waitFinishDialog, unBindSuccessDialog, unBindFailedDialog, coverDialog;

    private SwitchBindAdapter switchBindAdapter;

    private ObjectAnimator waitFinishAnimator;//等待解绑完成转圈动画
    private List<DeviceBindingData> mDeviceBingingData;//设备具体可以操作的开关

    private List<SwitchBindBean> switchBindBeans;
    private SwitchBindBean addSwitchBindBean;

    public static void startForDevice(Context context, String deviceSerialNo, String houseSerialNo, String deviceType, int deviceGroup) {
        Intent intent = new Intent(context, SwitchBindActivity.class);
        intent.putExtra("deviceType", deviceType);
        intent.putExtra("type", deviceGroup == 0 ? FROM_DEVICE : FROM_GROUP);
        intent.putExtra("deviceSerialNo", deviceSerialNo);
        intent.putExtra("houseSerialNo", houseSerialNo);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void startForScene(Context context, String sceneSerialNo, String houseSerialNo) {
        Intent intent = new Intent(context, SwitchBindActivity.class);
        intent.putExtra("type", FROM_SCENES);
        intent.putExtra("sceneSerialNo", sceneSerialNo);
        intent.putExtra("houseSerialNo", houseSerialNo);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void startForScene(BaseActivity activity, String sceneSerialNo, String houseSerialNo, int sceneType, BaseActivity.OnActivityCallback onActivityCallback) {
        Intent intent = new Intent(activity, SwitchBindActivity.class);
        intent.putExtra("type", FROM_SCENES);
        intent.putExtra("sceneType", sceneType);
        intent.putExtra("sceneSerialNo", sceneSerialNo);
        intent.putExtra("houseSerialNo", houseSerialNo);
        activity.startActivityForResult(intent, onActivityCallback);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_switch_bind;
    }

    @Override
    protected void initView() {
        type = getInt("type", -1);
        if (type == -1) {
            finish();
            return;
        }
        titleBar = findViewById(R.id.title_bar);
        titleBar.setRightTitleColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
        titleBar.setRightTitle(R.string.new_create);
        titleBar.getRightView().setVisibility(View.GONE);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View view) {
                onBackPressed();
            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {
                findViewById(R.id.add_switch_binding).performClick();
            }
        });
        operateBindView = findViewById(R.id.operate_bind_view);
        operateBindView.setCallback(new OperateBindView.Callback() {
            @Override
            public void requestInit(String statusKey, String statusValueName, Object statusValue, int bindActionType, int actionType) {
                SwitchBindBean switchBindBean = new SwitchBindBean();
                List<SwitchBindActionBean> bindActionBeans = new ArrayList<>();
                bindActionBeans.add(new SwitchBindActionBean());
                if (type == FROM_DEVICE){
                    bindActionBeans.get(0).setDeviceState(new DeviceState());
                    bindActionBeans.get(0).getDeviceState().setStatus(new DeviceState.StatusDTO(1));
                    if(statusKey.equals("color")){
                        Map<String,Integer> map = (Map<String, Integer>) statusValue;
                        bindActionBeans.get(0).getDeviceState().getStatus().setRed(map.get("red"));
                        bindActionBeans.get(0).getDeviceState().getStatus().setGreen(map.get("green"));
                        bindActionBeans.get(0).getDeviceState().getStatus().setBlue(map.get("blue"));
                    }else{
                        try {
                            Field field = bindActionBeans.get(0).getDeviceState().getStatus().getClass().getDeclaredField(statusKey);
                            field.setAccessible(true);
                            field.set(bindActionBeans.get(0).getDeviceState().getStatus(), (Integer) statusValue);
                        } catch (NoSuchFieldException | IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                    bindActionBeans.get(0).setDeviceSerialNo(bindSerialNo);
                    switchBindBean.setBindAction(bindActionBeans);//给设备绑定开关
                    String houseSerialNo = getString("houseSerialNo");
                    switchBindBean.setHouseSerialNo(houseSerialNo);//房间id
                    switchBindBean.setBindType(type);//1设备 2 场景
                    switchBindBean.setBindActionType(bindActionType);
                    switchBindBean.setActionType(actionType);
                    switchBindBean.setBindActionName(statusValueName);
                    switchBindBean.setBindSerialNo(bindSerialNo);
                } else if (type == FROM_SCENES){
                    if(!TextUtils.isEmpty(bindSerialNo)){
                        bindActionBeans.get(0).setSceneSerialNo(bindSerialNo);
                        switchBindBean.setBindAction(bindActionBeans);//给设备绑定开关
                    }
                    String houseSerialNo = getString("houseSerialNo");
                    switchBindBean.setHouseSerialNo(houseSerialNo);//房间id
                    switchBindBean.setBindType(type);//1设备 2 场景
                    switchBindBean.setBindActionType(0);
                    switchBindBean.setActionType(0);
                    switchBindBean.setBindSerialNo(bindSerialNo);
                }else if (type == FROM_GROUP){
                    bindActionBeans.get(0).setDeviceGroupState(new DeviceState());
                    bindActionBeans.get(0).getDeviceGroupState().setStatus(new DeviceState.StatusDTO(1));
                    try {
                        Field field = bindActionBeans.get(0).getDeviceGroupState().getStatus().getClass().getDeclaredField(statusKey);
                        field.setAccessible(true);
                        field.set(bindActionBeans.get(0).getDeviceGroupState().getStatus(), (Integer) statusValue);
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    bindActionBeans.get(0).setDeviceSerialNo(bindSerialNo);
                    switchBindBean.setBindAction(bindActionBeans);//给设备绑定开关
                    String houseSerialNo = getString("houseSerialNo");
                    switchBindBean.setHouseSerialNo(houseSerialNo);//房间id
                    switchBindBean.setBindType(type);//1设备 2 场景
                    switchBindBean.setBindActionType(bindActionType);
                    switchBindBean.setActionType(actionType);
                    switchBindBean.setBindActionName(statusValueName);
                    switchBindBean.setBindSerialNo(bindSerialNo);
                }
                LLHttpManager.addBindSwitch(SwitchBindActivity.this, switchBindBean, new HttpCallback<HttpData<SwitchBindBean>>(SwitchBindActivity.this) {
                    @Override
                    public void onSucceed(HttpData<SwitchBindBean> result) {
                        super.onSucceed(result);
                        if (result.getData() != null && result.getData().getCoreId() != null) {
                            //拿到CoreId后开始轮询等待服务器返回绑定成功 10秒后失败 3秒请求一次
                            operateBindView.startWait10SecondAnimator(result.getData().getCoreId());
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });
            }

            @Override
            public void requestInitQuery(String coreId) {
                LLHttpManager.queryBindSwitch(SwitchBindActivity.this, coreId, new HttpCallback<HttpData<SwitchBindBean>>(SwitchBindActivity.this) {
                    @Override
                    public void onSucceed(HttpData<SwitchBindBean> result) {
                        super.onSucceed(result);
                        if (result.getData() != null) {
                            switch (result.getData().getBindSateType()) {
                                case 1://继续轮询等待
                                    break;
                                case 2://绑定成功
                                    operateBindView.bindComplete();
                                    //把绑定成功的添加到当前列表
                                    switchBindBeans.add(result.getData());
                                    buildUIData(switchBindBeans);
                                    setResult(RESULT_OK);
                                    break;
                                case 3://绑定失败
                                case 4://绑定超时
                                    operateBindView.failedBind();
                                    break;
                                case 5://绑定设备不存在
                                    //showConfirmCancelHintDialog();
                                    toast("设备不存在");
                                    finish();
                                case 6://覆盖绑定成功
                                    operateBindView.coverComplete();
                                    coverReplace();
                                    buildUIData(switchBindBeans);
                                    setResult(RESULT_OK);
                                    break;
                                case 7://存在绑定
                                    addSwitchBindBean = result.getData();
                                    operateBindView.hasBind();
                                    coverDialog.show();
                                    operateBindView.endWait();
                                    break;
                            }
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });
            }
        });
        //这里是根据进来的是设备或者场景控制不同的空页面显示
        setImageViewBind(R.id.img_switch_binging_empty, type != FROM_SCENES
                ? AppApplication.getInstance().getThemeDrawable(R.attr.icon_me_switchthebinding) : AppApplication.getInstance().getThemeDrawable(R.attr.icon_me_switchthebinding_2));
        setTextViewBind(R.id.tv_switch_binging_empty, type != FROM_SCENES ? R.string.switch_binding_empty_by_device : R.string.switch_binding_empty_by_scenes);
        setVisibilityBind(R.id.empty_group, View.VISIBLE);
        waitFinishDialog = new WaitFinishDialog.Builder(this)
                //.setIconWait(R.attr.icon_remind_load)
                .setTvContent(R.string.unbind_running)
                .create();

        unBindSuccessDialog = new ConfirmHintDialog.Builder(this)
                .setHint(getString(R.string.unbind_switch_success))
                //.setContent(String.format(getString(R.string.few_second_try), "3"))
                .setRightBtnText(getResources().getString(R.string.common_confirm))
                .setHintIcon(R.attr.icon_remind_correct)
                .create();

        unBindFailedDialog = new ConfirmHintDialog.Builder(this)
                .setHint(getString(R.string.unbind_switch_failed))
                .setContent(getString(R.string.please_after_try))
                .setHintIcon(R.attr.icon_remind_fail)
                .setRightBtnText(getResources().getString(R.string.common_confirm))
                .setRightBtnBackground(R.drawable.btn_secondary_color1_4dp)
                .create();

        coverDialog = new ConfirmCancelHintDialog.Builder(this)
                .setContent(R.string.switch_binding_cover_tip)
                .setRightText(R.string.fugai)
                .setRightBtnBackground(R.drawable.btn_theme_round_4dp)
                .setListener(new ConfirmCancelHintDialog.OnListener() {
                    @Override
                    public void onLeftClick(BaseDialog dialog) {
                        LLHttpManager.enterswitchbind(SwitchBindActivity.this, operateBindView.coreId, 0, new HttpCallback<HttpData<Void>>(SwitchBindActivity.this){
                            @Override
                            public void onSucceed(HttpData<Void> result) {
                                super.onSucceed(result);
                                operateBindView.setVisibility(View.GONE);
                            }
                        });
                    }

                    @Override
                    public void onRightClick(BaseDialog dialog) {
                        LLHttpManager.enterswitchbind(SwitchBindActivity.this, operateBindView.coreId, 1, new HttpCallback<HttpData<Void>>(SwitchBindActivity.this){
                            @Override
                            public void onSucceed(HttpData<Void> result) {
                                super.onSucceed(result);
                                operateBindView.coverComplete();
                                coverReplace();
                                buildUIData(switchBindBeans);
                                setResult(RESULT_OK);
                            }
                        });
                    }
                })
                .create();
        recyclerView = findViewById(R.id.recycler_view);
        setOnClickListener(R.id.add_switch_binding);
    }

    public void coverReplace(){
        boolean replaced = false;
        for (int i = 0; i <switchBindBeans.size(); i++) {
            SwitchBindBean bean = switchBindBeans.get(i);
            String addStr = addSwitchBindBean.getSwitchAction().get(0).getState();
            String beanStr = bean.getSwitchAction().get(0).getState();

            if (addStr.equals(beanStr)){
                switchBindBeans.set(i, addSwitchBindBean);
                replaced = true;
            }
        }
        if (!replaced){
            switchBindBeans.add(addSwitchBindBean);
        }
    }



    private void showWaitFinishDialog() {
        waitFinishDialog.show();

        if (waitFinishAnimator == null) {
            waitFinishAnimator = ObjectAnimator.ofFloat(waitFinishDialog.findViewById(R.id.icon_wait), "rotation", 0f, 360f)
                    .setDuration(1000);
            waitFinishAnimator.setRepeatCount(1000);
            waitFinishAnimator.setRepeatMode(ValueAnimator.RESTART);
            waitFinishAnimator.start();
            return;
        }
        waitFinishAnimator.cancel();
        waitFinishAnimator.start();

    }

    private void disWaitFinishDialog() {
        if (waitFinishDialog.isShowing()) {
            waitFinishAnimator.cancel();
            waitFinishDialog.dismiss();

        }
    }

    private String bindSerialNo;//绑定的设备唯一码
    @Override
    protected void initData() {
        switchBindBeans = new ArrayList<>();
        if (FROM_DEVICE == type || FROM_GROUP == type){
            String deviceSerialNo = getString("deviceSerialNo");
            bindSerialNo = deviceSerialNo;
            DeviceBean deviceBean = LLDeviceDBManager.getInstance(this).get(deviceSerialNo);
            DeviceBaseConfigInfo deviceBaseConfigInfo = DeviceInfoParseUtil.parseData(getContext(), deviceBean.getDeviceType(), DeviceBaseConfigInfo.class);
            mDeviceBingingData = deviceBaseConfigInfo.getBingingData();
            if(deviceBean.getType().equals("universal") || deviceBean.getDeviceType().equals("universal_freshair")){
                List<UniversalDeviceData> datas = LLDeviceActionDBManager.getInstance(this).getEnalbeDeviceDatasByDeviceSerialNo(deviceSerialNo);
                mDeviceBingingData = new ArrayList<>();
                DeviceBindingData bindingData = new DeviceBindingData();
                bindingData.setKey("operation");
                bindingData.setName("操作");
                bindingData.setBingingType(0);
                bindingData.setActionType(1);
                List<DeviceBindingData.Data> bingingDatas = new ArrayList<>();
                for(UniversalDeviceData data : datas){
                    DeviceBindingData.Data newData = new DeviceBindingData.Data();
                    if(deviceBean.getDeviceType().equals("universal_sequencer")){
                        newData.setName(String.format("%s:%s",data.getCombineName(),data.getRangeName()));
                    }else if(deviceBean.getDeviceType().equals("universal_freshair")){
                        newData.setName(String.format("%s:%s",data.getActionName(),data.getRangeName()));
                    }else{
                        newData.setName(data.getRangeName());
                    }
                    newData.setValue(Integer.parseInt(data.getRangeIdentifier()));
                    newData.setBindActionType(Integer.parseInt(data.getRangeIdentifier()));
                    bingingDatas.add(newData);
                }
                bindingData.setData(bingingDatas);
                mDeviceBingingData.add(bindingData);
            }

            if (mDeviceBingingData == null || mDeviceBingingData.size() == 0) {
                Log.e("无法设置开关绑定的设备类型", getString("deviceType"));
                finish();
                return;
            }
            String deviceType = deviceBean.getDeviceType();
            if (deviceType.equals("wireless_433_key_3") || deviceType.equals("wireless_315_key_3") || deviceType.equals("infra-red_key_9")){
                getDeviceCustomKeyList(deviceBean);
            }else {
                operateBindView.setInfoBean(mDeviceBingingData);
            }

        }else if (FROM_SCENES == type){
            bindSerialNo = getString("sceneSerialNo");
            operateBindView.setInfoBean(null);
            mDeviceBingingData = new ArrayList<>();
            DeviceBindingData deviceBindingData = new DeviceBindingData();
            deviceBindingData.setName("execute");
            mDeviceBingingData.add(deviceBindingData);
        }
        LLHttpManager.getSwitchBind(this, bindSerialNo, new HttpCallback<HttpData<List<SwitchBindBean>>>(this) {
            @Override
            public void onSucceed(HttpData<List<SwitchBindBean>> result) {
                super.onSucceed(result);
                if (result.getData().size() > 0) {//存在数据则把空页面隐藏
                    titleBar.post(new Runnable() {
                        @Override
                        public void run() {
                            titleBar.getRightView().setVisibility(View.VISIBLE);
                            findViewById(R.id.empty_group).setVisibility(View.GONE);
                        }
                    });
                    switchBindBeans = result.getData();
                    buildUIData(switchBindBeans);
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }
        });
    }

    private boolean getCanCustomKeyName(DeviceBean deviceBean){
        String keyValue = LLDeviceUtil.getDeviceType(deviceBean.getDeviceType()).getDeviceTypeInfo("custom");
        if ("1".equals(keyValue)){
            return true;
        }
        return false;
    }

    private void getDeviceCustomKeyList(DeviceBean deviceBean){
        DeviceBindingData bindingData = mDeviceBingingData.get(0);
        List<DeviceBindingData.Data> datas = bindingData.getData();
         List<DeviceCustomKeyBean> customKeyList = LLDeviceCustomDBManager.getInstance(getContext()).getDataByDeviceSerialNo(deviceBean.getDeviceSerialNo());
        deviceBean.setDeviceCustomKeys(customKeyList);
        for(int i = 0;i < datas.size();i++){
            DeviceBindingData.Data data = datas.get(i);
            for(int j = 0;j < customKeyList.size();j++){
                DeviceCustomKeyBean keyBean = customKeyList.get(j);
                if(data.getValue() == Integer.parseInt(keyBean.getKeyIndex())){
                    data.setName(keyBean.getKeyName());
                    mDeviceBingingData.get(0).getData().set(i,data);
                    break;
                }
            }
        }
        operateBindView.setInfoBean(mDeviceBingingData);
    }

    private String getUnit(SwitchBindBean bean){
        if (mDeviceBingingData == null || mDeviceBingingData.isEmpty()) return "";
        for (DeviceBindingData type : mDeviceBingingData){
            if (type.getActionType() == bean.getActionType()){
                return type.getUnit();
            }
        }
        return "";
    }

    private String getName(SwitchBindBean bean){
        if (mDeviceBingingData == null || mDeviceBingingData.isEmpty()) return "";

        for (DeviceBindingData type : mDeviceBingingData){
            if (type.getActionType() == bean.getActionType()){
                for (DeviceBindingData.Data data : type.getData()){
                    if (data.getBindActionType() == bean.getBindActionType()){
                        try {
                            int valueId = getResources().getIdentifier(data.getName(), "string", getContext().getPackageName());
                            return getResources().getString(valueId);
                        }catch (Resources.NotFoundException e){
                            return data.getName();
                        }

                    }
                }
            }
        }
        return "";
    }

    private int getBindType(SwitchBindBean bean){
        for (DeviceBindingData data : mDeviceBingingData){
            if (bean.getActionType() == data.getActionType()){
                return data.getBingingType();
            }
        }
        return -1;
    }

    private void buildUIData(List<SwitchBindBean> switchBindBeans) {
        List<UISwitchBindBean> uiSwitchBindBeans = new ArrayList<>();
        if (type == FROM_SCENES){
            UISwitchBindBean uiSwitchBindBean = new UISwitchBindBean();
            uiSwitchBindBean.setBindActionName(getString(R.string.execute));
            uiSwitchBindBean.setSwitchBindBeans(switchBindBeans);
            uiSwitchBindBeans.add(uiSwitchBindBean);
        }else if (type == FROM_DEVICE || type == FROM_GROUP){
            if(mDeviceBingingData == null || switchBindBeans == null){
                return;
            }
            LinkedHashMap<String, ArrayList<SwitchBindBean>> uiSwitchBindMap = new LinkedHashMap<>();
            for (SwitchBindBean bean : switchBindBeans){
                String title = "";
                if (1 == getBindType(bean)){//范围类型
                    title = bean.getBindActionType() + getUnit(bean);
                }else if (0 == getBindType(bean)){//枚举类型
                    title = getName(bean);
                }
                if (!TextUtils.isEmpty(title)){
                    ArrayList<SwitchBindBean> list = uiSwitchBindMap.get(title);
                    if (list == null){
                        list = new ArrayList<>();
                        list.add(bean);
                        uiSwitchBindMap.put(title, list);
                    }else {
                        list.add(bean);
                    }
                }
            }
            for (String title : uiSwitchBindMap.keySet()){
                UISwitchBindBean uiSwitchBindBean = new UISwitchBindBean();
                uiSwitchBindBean.setBindActionName(title);
                uiSwitchBindBean.setSwitchBindBeans(uiSwitchBindMap.get(title));
                uiSwitchBindBeans.add(uiSwitchBindBean);
            }
        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /*for (DeviceBindingData bingingData : mDeviceBingingData) {
            if (bingingData.getData() != null && bingingData.getData().size() > 0) {
                for (DeviceBindingData.Data data : bingingData.getData()) {
                    List<SwitchBindBean> switchBindBeanList = LambdaUtils.findAll(switchBindBeans, bean -> bean.getBindActionType() == data.getBindActionType());//第一个是开关
                    if (switchBindBeanList.size() == 0)
                        continue;
                    UISwitchBindBean uiSwitchBindBean = new UISwitchBindBean();
                    uiSwitchBindBean.setBindActionName(data.getName());
                    uiSwitchBindBean.setBindActionType(data.getBindActionType());
                    uiSwitchBindBean.setActionType(switchBindBeanList.get(0).getActionType());
                    uiSwitchBindBean.setSwitchBindBeans(switchBindBeanList);
                    uiSwitchBindBeans.add(uiSwitchBindBean);
                }
            } else {
                List<SwitchBindBean> switchBindBeanList = LambdaUtils.findAll(switchBindBeans, bean -> bean.getActionType() == bingingData.getActionType());//模式
                if (switchBindBeanList.size() == 0)//模式下没有数据 跳过
                    continue;
                UISwitchBindBean uiSwitchBindBean = new UISwitchBindBean();
                uiSwitchBindBean.setBindActionName(bingingData.getName());
                uiSwitchBindBean.setActionType(bingingData.getActionType());
                uiSwitchBindBean.setSwitchBindBeans(switchBindBeanList);
                uiSwitchBindBeans.add(uiSwitchBindBean);
            }
        }*/
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


        if (uiSwitchBindBeans.isEmpty()){
            setVisibilityBind(R.id.empty_group, View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            titleBar.getRightView().setVisibility(View.GONE);
        }else {
            setVisibilityBind(R.id.empty_group, View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            titleBar.getRightView().setVisibility(View.VISIBLE);
        }
        switchBindAdapter = new SwitchBindAdapter(SwitchBindActivity.this, bean -> {
            //先弹窗
            showConfirmCancelHintDialog(R.attr.icon_remind_hint, getString(R.string.hint_notice)
                    , getString(R.string.unbind_warning_tip), getString(R.string.close)
                    , getString(R.string.ok), new ConfirmCancelHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                            dialog.dismiss();
                        }

                        @Override
                        public void onRightClick(BaseDialog dialog) {
                            dialog.dismiss();
                            unbindSwitch(bean);
                        }
                    });

        });
        switchBindAdapter.setData(uiSwitchBindBeans);
        recyclerView.setAdapter(switchBindAdapter);
        if (type == FROM_SCENES){
            SceneDetailBean sceneDetailBean = TempDataHolder.getEditSceneDetailBean(getInt("sceneType", 1));
            if(sceneDetailBean != null){
                sceneDetailBean.setSwitchBindList(switchBindBeans);
            }
        }
    }

    private void unbindSwitch(SwitchBindBean bean) {
        showWaitFinishDialog();
        List<String> serialNoList = new ArrayList<>();
        serialNoList.add(bean.getSwitchBindSerialNo());

        LLHttpManager.deleteBindSwitch(SwitchBindActivity.this, serialNoList, new HttpCallback<HttpData<QueryCodeResultBean>>(SwitchBindActivity.this) {
            @Override
            public void onSucceed(HttpData<QueryCodeResultBean> result) {
                super.onSucceed(result);
                switch (result.getData().getQueryStateType()) {
                    case 0://发起操作
                    case 1://正在操作
                        postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                unbindWaitResult(bean,result.getData());//2秒后去问一下解绑成功没有
                            }
                        }, 2000);
                        break;
                    case 2://操作成功
                        unBindSuccess(bean.getSwitchBindSerialNo());
                        break;
                    case 3://操作失败
                    case 4://操作异常
                        disWaitFinishDialog();
                        //弹出解绑异常
                        unBindFailedDialog.show();
                        break;
                }

            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
                disWaitFinishDialog();
                //这里需要弹出失败弹窗
                unBindFailedDialog.show();
            }
        });
    }

    private void unbindWaitResult(SwitchBindBean bean, QueryCodeResultBean data) {
        LLHttpManager.deleteBindSwitchQuery(this, data.getQueryCode(), new HttpCallback<HttpData<QueryCodeResultBean>>(this) {
            @Override
            public void onSucceed(HttpData<QueryCodeResultBean> result) {
                super.onSucceed(result);
                switch (result.getData().getQueryStateType()) {
                    case 0://发起操作
                    case 1://正在操作
                        postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                unbindWaitResult(bean,result.getData());//2秒后去问一下解绑成功没有
                            }
                        }, 2000);
                        break;
                    case 2://操作成功
                        unBindSuccess(bean.getSwitchBindSerialNo());
                        break;
                    case 3://操作失败
                    case 4://操作异常
                        disWaitFinishDialog();
                        //弹出解绑异常
                        unBindFailedDialog.show();
                        break;
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
                //弹出解绑异常
            }
        });
    }

    /**
     * 解绑成功 更新UI
     */
    private void unBindSuccess(String switchBindSerialNo) {
        for (int i = 0; i < switchBindBeans.size(); i++) {
            SwitchBindBean bean = switchBindBeans.get(i);
            if (bean.getSwitchBindSerialNo().equals(switchBindSerialNo)){
                switchBindBeans.remove(i);
            }
        }
        buildUIData(switchBindBeans);
        setResult(RESULT_OK);
        //switchBindAdapter.removeSwitchBindBean(switchBindId);//适配器中移出当前绑定开关
        disWaitFinishDialog();

        //弹出解绑成功
        unBindSuccessDialog.show(3, new BaseDialog.DelayTimeCallBack() {
            @Override
            public void callback(int time) {
                TextView textView = unBindSuccessDialog.getContentView().findViewById(R.id.tv_content);
                textView.setText(String.format(getString(R.string.few_second_try), ""+time));
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_switch_binding:
                if (operateBindView.getVisibility() == View.GONE) {
                    operateBindView.setVisibility(View.VISIBLE);
                }
                break;
        }

    }

    @Override
    public void onBackPressed() {
        if (operateBindView.getVisibility() == View.VISIBLE) {
            operateBindView.setVisibility(View.GONE);
            return;
        }
        super.onBackPressed();

    }
}
